#pragma once

#include <iostream>
#include <cstring>
#include <string>
#include <unordered_map>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"

// typedef std::function<std::string(const std::string &, const std::string &, uint16_t)> func_t;

std::string defaultip = "0.0.0.0";
uint16_t defaultport = 8888;
const int size = 1024;

Log log;
enum
{
    SOCKET_ERR = 1,
    BIND_ERR,
};

class UdpServer
{
public:
    UdpServer(const uint16_t &port = defaultport, const std::string &ip = defaultip) : ip_(ip), port_(port), isrunning(false)
    {
    }
    void Init()
    {
        // 1.创建udp socket
        //   Udp 的socket是全双工的，允许被同时读写的
        socketfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if (socketfd_ < 0)
        {
            log(Fatal, "create socket erro,socketfd:%d", socketfd_);
            exit(SOCKET_ERR);
        }
        log(Info, "socket create success, socketfd: %d", socketfd_);

        // 2.绑定socket
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);                  // 需要保证我的端口号是网络字节序列，因为该端口号是要给对方发送的
        local.sin_addr.s_addr = inet_addr(ip_.c_str()); // 1. string -> uint32_t 2. uint32_t必须是网络序列的
        // local.sin_addr.s_addr=htonl(INADDR_ANY);//或者这样

        if (bind(socketfd_, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            log(Fatal, "bind error, errno: %d, err string: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        log(Info, "bind success, errno: %d, err string: %s", errno, strerror(errno));
    }
    void ChectUser(const struct sockaddr_in &client, uint16_t clientport, const std::string &clientip)
    {
        auto it = online_user_.find(clientip);
        if (it == online_user_.end())
        {
            online_user_.insert({clientip, client});
            std::cout << "[" << clientip << ":" << clientport << "]" << "add to online user" << std::endl;
        }
    }

    void BroadCast(const std::string &info, uint16_t clientport, const std::string &clientip)
    {
        for (const auto &users : online_user_)
        {
            std::string massege = "[";
            massege += clientip;
            massege += ":";
            massege += to_string(clientport);
            massege += "]# ";
            massege += info;
            socklen_t len = sizeof(users.second);
            sendto(socketfd_, massege.c_str(), massege.size(), 0, (struct sockaddr *)&users.second, len);
        }
    }
    void Run()
    {
        isrunning = true;
        char buff[size];
        while (true)
        {
            memset(buff,0,size);
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(socketfd_, buff, sizeof(buff) - 1, 0, (struct sockaddr *)&client, &len);
            if (n < 0)
            {
                log(Warning, "recvfrom error, errno: %d, err string: %s", errno, strerror(errno));
                continue;
            }
            uint16_t clientport = ntohs(client.sin_port);
            std::string clientip = inet_ntoa(client.sin_addr);
            ChectUser(client, clientport, clientip);

            std::string info = buff;
            BroadCast(info, clientport, clientip);
        }
    }
    ~UdpServer()
    {
    }

private:
    int socketfd_;   // 网络文件描述符
    std::string ip_; // 绑定的IP地址
    uint16_t port_;  // 绑定的端口号
    bool isrunning;
    std::unordered_map<std::string, struct sockaddr_in> online_user_; // 存在线用户
};
